package com.magupe.develop.udp.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpChatClient {

    public void run(int port) {
        EventLoopGroup group=new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpChatClientHandler());
            Channel ch = b.bind(0).sync().channel();

            InetSocketAddress address = new InetSocketAddress("192.168.2.228", port);
            DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer("abc", CharsetUtil.UTF_8), address);
            ch.writeAndFlush(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new UdpChatClient().run(8888);
    }
}
